import { AuditOption } from './../model/auditOption';
import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, HostListener, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { chunk } from 'lodash';
import { AuditItem } from '../model/auditItem';

@Component({
  selector: 'zepride-audit-record',
  templateUrl: './audit-record.component.html',
  styleUrls: ['./audit-record.component.less']
})
export class AuditRecordComponent implements OnInit, AfterViewInit, OnDestroy {

  @Input() options: AuditOption = {
    auditLevel: 1,
    auditItems: []
  };
  itemsRows: AuditItem[][] = [];
  @Input() readonly = false;
  @ViewChild('itemWrapper') itemWrapper: ElementRef<HTMLDivElement>;
  itemWidth = 200;
  itemHeight = 150;
  resize$: Subscription;
  style = {
    width: `${this.itemWidth}px`,
    height: `${this.itemHeight}px`
  };

  constructor(
    private changeRef: ChangeDetectorRef
  ) { }

  ngOnInit(): void { }

  ngAfterViewInit() {
    this.calcLayout();
    this.registerResize();
  }

  calcLayout() {
    const container = this.itemWrapper.nativeElement;
    if (!container) {
      return;
    }
    const width = container.offsetWidth;
    const items = this.options.auditItems;
    const firstItem = items[0];
    const restItems = items.slice(1);
    /**
     * 一行的个数，第一行会多一个元素
     */
    let numOfOneRow = Math.floor((width - this.itemWidth) / this.itemWidth);
    numOfOneRow = numOfOneRow <= 0 ? 1 : numOfOneRow;
    let rows = chunk(restItems, numOfOneRow);
    rows[0].unshift(firstItem);
    const length = rows.length;
    rows = rows.map((row, index) => {
      if (index > 0) {
        const emptyNode: AuditItem = { isEmptyNode: true };
        if (index % 2 > 0 && index !== length - 1) {
          row.push(emptyNode);
        } else if (index % 2 === 0 && row.length <= numOfOneRow + 1) {
          const diff = numOfOneRow - row.length;
          const emptyNodes = new Array(diff).fill({ ...emptyNode, noBorder: true });
          row = [emptyNode, ...row, ...emptyNodes];
        }
      }
      return row;
    });
    this.itemsRows = rows;
    this.changeRef.detectChanges();
  }

  registerResize() {
    this.resize$ = fromEvent(window, 'resize').pipe(
      debounceTime(100)
    ).subscribe(() => {
      this.calcLayout();
    });
  }

  ngOnDestroy() {
    if (this.resize$) {
      this.resize$.unsubscribe();
    }
  }
}


